package tools

import (
	"gitee.com/lllgo/gopkg/template"
	"gitee.com/lllgo/gopkg/utils"
	"strings"
)

var (
	allHost   map[string]Host
	cacheHost map[string][]Host
)

func SetAllHostsUseFile(file string) (err error) {
	if allHost, err = Parse(file); err == nil {
		err = template.AddMetaData(templateHostKey, allHost)
	}
	return
}

func SetAllHosts(content string) (err error) {
	allHost, err = ParseContent(content)
	err = template.AddMetaData(templateHostKey, allHost)
	return
}

// name可以是组名或标签名
func getHost(name string) []Host {
	if host, ok := allHost[name]; ok {
		return []Host{host}
	}

	var hs []Host
	for _, host := range allHost {
		if utils.ContainsString(host.Group, name) {
			hs = append(hs, host)
		}
	}
	return hs
}

// names可以是组名或标签名
func GetHosts(names ...string) []Host {
	return GetHostsWithFunc(nil, names...)
}

func GetAllHosts() (hs []Host) {
	for _, host := range allHost {
		hs = append(hs, host)
	}
	return
}

func GetHostsWithFunc(f func(host Host), names ...string) []Host {
	if len(names) > 0 {
		key := strings.Join(names, ",")
		if cache, ok := cacheHost[key]; ok {
			return cache
		}

		var hs []Host
		var ips []string
		for _, n := range names {
			for _, host := range getHost(n) {
				ip := host.IP()
				if !utils.ContainsString(ips, ip) {
					hs = append(hs, host)
					ips = append(ips, ip)
					if f != nil {
						f(host)
					}
				}
			}
		}

		return hs
	}
	return nil
}
